﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using eWorld.UI;
using System.Threading;
using System.IO;
using System.Drawing;
using ZX.CRM.Library;
using ZX.CRM.Bussiness;
using System.Collections.Generic;
using System.Linq;
//using lite;
namespace ZX.WebApp.Crm.BasePages
{
    public partial class BasePages_WorkTaskCtrlPage : ZX.Web.UI.Controls.BasePage
    {
        string UserId = "";


        string pageState = "";//新建,修改,查看
        string OperStatus = "";//操作状态,0 未处理未认领，1处理完成，2指派他人，3认领未处理
        ArrayList UserCtrlList = new ArrayList();//控件列表
        ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();


        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle
        {
            get
            {
                return Request["title"] == null ? "" : Request["title"].ToString();
            }
        }

        /// <summary>
        /// 表名
        /// </summary>
        public string TableName
        {
            get;
            set;
        }
        /// <summary>
        /// id
        /// </summary>
        public string KeyValue
        {
            get;
            set;
        }
        /// <summary>
        /// 流程ID
        /// </summary>
        public string WorkFlowId
        {
            get;
            set;
        }
        /// <summary>
        /// 流程务任ID
        /// </summary>
        public string WorkTaskId
        {
            get;
            set;
        }
        /// <summary>
        /// 表单类型
        /// </summary>
        public string FormType
        {
            get;
            set;
        }


        /// <summary>
        /// 流程实例ID
        /// </summary>
        public string WorkFlowInsId
        {
            get;
            set;
        }
        /// <summary>
        /// 流程任务实例ID
        /// </summary>
        public string WorkTaskInsId
        {
            get;
            set;
        }
        /// <summary>
        /// 
        /// </summary>
        public string OperatorInsId
        {
            get;
            set;
        }
        /// <summary>
        /// 流程状态
        /// </summary>
        public string Status
        {
            get;
            set;
        }

        public string OperTypeStatus
        {
            get;
            set;
        }
        /// <summary>
        /// 流程类型
        /// </summary>
        public string OperType
        {
            get;
            set;
        }
        /// <summary>
        /// 是否草稿
        /// </summary>
        public string IsDraft
        {
            get;
            set;
        }
        public string IsIE
        {
            get
            {
                string isIE = "1";
                bool ise=UserPoint();
                isIE = (UserPoint()) ? "0" : "1";
                return isIE;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                if (this.Session["User"] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }

                if (!IsPostBack)
                //BaseUserPage.LoadWaitPage();//必须加在 这里，否则打印时出现正在加载对话框
                {
                    UserId = this.Page.User.Identity.Name;
                }
                if (Request["WorkTaskInstanceId"] != null && UserId != "")
                    client.GetWorkFlowDisplay(Request["WorkTaskInstanceId"].ToString(), UserId);
                GetWorkTaskOperType();
                InitData();
            }
            catch (Exception ex)
            {
                //LogData.WriteLog("平台打开处理界面错误:" + ex, WorkflowInsId);
                throw ex;
            }
            finally
            {
                //if (!IsPostBack)
                   // BaseUserPage.FreeWaitPage();
            }


        }

        public string URL
        {
            get;
            set;
        }
        private void InitData()
        
        {
            if (Request["state"] != null)
            {
                pageState = Request["state"].ToString();
            }
            if (Request["OperatorInstanceId"] != null)
            {
                OperatorInsId = Request["OperatorInstanceId"].ToString();
                DataTable dt = client.GetOperatorInstanceView(OperatorInsId);
                bool islock = true;
         
                if (dt != null && dt.Rows.Count > 0)
                {
                    islock = client.IsLock(dt.Rows[0]["WorkTaskInstanceId"].ToString());
                    WorkFlowId = dt.Rows[0]["WorkflowId"].ToString();
                  
                    WorkTaskId = dt.Rows[0]["WorktaskId"].ToString();
                    if (dt.Rows[0]["flStatus"].ToString() == "3")
                    {
                        Status = dt.Rows[0]["flStatus"].ToString();
                    }
                    else if (islock == false)
                    {
                        Status = "2";
                    }
                    else
                    {
                        Status = dt.Rows[0]["Status"].ToString();
                    }
                    OperType = dt.Rows[0]["OperType"].ToString();
                    WorkFlowInsId = dt.Rows[0]["WorkFlowInstanceId"].ToString();
                    WorkTaskInsId = dt.Rows[0]["WorkTaskInstanceId"].ToString();
                    OperStatus = dt.Rows[0]["OperStatus"].ToString();
                    DataTable cdt = client.GetWorkTaskFormsView(WorkTaskId);
                    DataTable wtdt = client.GetWorkTaskInstanceView(WorkTaskInsId);
                    if (wtdt.Rows.Count > 0)
                    {

                        if (wtdt.Rows[0]["TaskTypeId"].ToString() == "1" && wtdt.Rows[0]["OperStatus"].ToString() == "3" && wtdt.Rows[0]["Status"].ToString() == "2")
                        {
                            IsDraft = "1";
                        }
                        else { IsDraft = "0"; }
                    }

                    if (cdt != null && cdt.Rows.Count > 0)
                    {
                        FormType = cdt.Rows[0]["FormType"].ToString();

                        switch (FormType)
                        {
                            case "Html":
                                DataTable sysForm = client.GetTableEntity(cdt.Rows[0]["FilePath"].ToString());
                                string entityName = sysForm.Rows[0]["MasterTableName"].ToString();
                                string formid = sysForm.Rows[0]["FormID"].ToString();
                                string id = ReturnPayId(WorkFlowInsId, entityName);

                                if (Status == "3")
                                {
                                    DataTable netTaskins = client.GetNetTaskFormID(WorkTaskInsId, WorkTaskId);
                                    if (netTaskins.Rows.Count > 0)
                                    {
                                        WorkTaskId = netTaskins.Rows[0]["workTaskId"].ToString();
                                        formid = netTaskins.Rows[0]["FilePath"].ToString();
                                    }
                                }
                                URL = "../../Extend/AutoLoadForm.aspx?entity=" + entityName + "&action=Select&formid=" + formid + "&id=" + id + "&workflowid=" + WorkFlowId + "&worktaskid=" + WorkTaskId + "&statues=" + Status;
                                //powerButton();//根据控制权限创建的按钮                                
                                break;
                            case "Page":
                                string url = cdt.Rows[0]["FilePath"].ToString().Replace('\\', '/');
                                
#region //原来流程从这儿跳转，保持流程不变化；跳转框架内进行审核，需要参数不改变，进行下面处理。

                                string strEntity = cdt.Rows[0]["ChildCaption"].ToString();
                                string strWorkFlowEntity = System.Configuration.ConfigurationManager.AppSettings["WorkFlowEntity"];
                                string[] str = strWorkFlowEntity.Split('|');
                                List<string> lsCode =new List<string>(str);
                                bool flg = lsCode.Any(o => o == strEntity);
                                if (flg)
                                    url = "/Extend/AutoLoadForm.aspx";
                                else
                                    url = string.Format("../{0}", url);
#endregion

                                BCrmDeliverMajor bcd = new BCrmDeliverMajor();
                                DataTable descript= bcd.GetTaskById(WorkTaskId);
                                string strDescript = "";
                                if (descript != null && descript.Rows.Count > 0) { strDescript = descript.Rows[0][0].ToString(); }
                               //Server.Transfer("../" + url);
                                if (Request["view"] != null)
                                {
                                    url += "?view=" + Request["view"].ToString() + "&descript=" + strDescript + "&flag=1&WorktaskId=" + WorkTaskId + "&WorkflowInsId=" + WorkFlowInsId + "&OperatorInstanceId=" + OperatorInsId + "&entity=" + Server.UrlEncode(cdt.Rows[0]["ChildCaption"].ToString()) + "&WorktaskInsId=" + WorkTaskInsId + "&title=" + Server.UrlEncode("流程处理") + "&OperStatus=" + OperStatus + "&WorkflowId=" + WorkFlowId + "&statues=" + Status;
                                }
                                else
                                {
                                    url += "?flag=1&descript=" + strDescript + "&WorktaskId=" + WorkTaskId + "&WorkflowInsId=" + WorkFlowInsId + "&OperatorInstanceId=" + OperatorInsId + "&entity=" + Server.UrlEncode(cdt.Rows[0]["ChildCaption"].ToString()) + "&WorktaskInsId=" + WorkTaskInsId + "&title=" + Server.UrlEncode("流程处理") + "&OperStatus=" + OperStatus + "&WorkflowId=" + WorkFlowId + "&statues=" + Status;
                                }
                                URL =   url;
                                //Server.Execute("../" + url);
                                //Response.Redirect("~../crm/"+url);
                                break;
                            case "URL":
                                URL = cdt.Rows[0]["FilePath"].ToString();
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

        }
        public void GetWorkTaskOperType()
        {
            if (Request["OperatorInstanceId"] != null)
            {
                DataTable dt = client.GetOperatorInstanceView(Request["OperatorInstanceId"].ToString());
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["OperType"].ToString() == "12")
                    {
                        OperTypeStatus = "1";
                    }
                   
                }
            }
            
        }
        ////动态加载任务命令按钮,退回,指派，动态指定下一任务处理人按钮
        ///// <summary>
        ///// 根据权限加载 退回,指派，动态指定下一任务处理人按钮
        ///// </summary>
        //private void powerButton()
        //{
        //    string powerStr = "";
        //    DataTable dt = client.GetTaskPowers(WorktaskId);
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        powerStr = powerStr + dr["PowerName"].ToString() + ",";
        //    }
        //    if (powerStr.IndexOf(WorkFlowConst.WorkTask_Return) > -1)//允许退回
        //    {
        //        Button btnCommand = new Button();
        //        btnCommand.Text = "退回";
        //        btnCommand.Click += new EventHandler(taskBackButtonEvent);
        //        btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
        //        cmdBtnPlace.Controls.Add(btnCommand);
        //        Literal lab1 = new Literal();
        //        lab1.Text = "&nbsp;&nbsp;";
        //        cmdBtnPlace.Controls.Add(lab1);
        //    }
        //    if (powerStr.IndexOf(WorkFlowConst.WorkTask_Assign) > -1)//允许指派
        //    {
        //        Button btnCommand = new Button();
        //        btnCommand.Text = "指派";
        //        btnCommand.Click += new EventHandler(taskAssignButtonEvent);
        //        btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
        //        cmdBtnPlace.Controls.Add(btnCommand);
        //        Literal lab1 = new Literal();
        //        lab1.Text = "&nbsp;&nbsp;";
        //        cmdBtnPlace.Controls.Add(lab1);
        //    }
        //    if (powerStr.IndexOf(WorkFlowConst.WorkTask_DyAssignNext) > -1)//允许动态指定下一步处理人
        //    {
        //        BaseUserControl c = (BaseUserControl)this.LoadControl(@"..\BaseUserControls\DyAssignNext.ascx");
        //        c.WorkflowId = WorkflowId;
        //        c.ID = "nextCtrl";//必须指定名称。js代码才能取到
        //        c.PageState = pageState;
        //        c.CtrlState = WorkFlowConst.STATE_MOD;
        //        c.WorkflowInsId = WorkflowInsId;
        //        c.WorktaskId = WorktaskId;
        //        c.WorktaskInsId = WorktaskInsId;
        //        c.OperatorInsId = OperatorInsId;
        //        c.InitUserControl();//执行控件的初始化事件
        //        UserCtrlList.Add(c);//加到用户控件列表中
        //        DyAssignPlace.Controls.Add(c);

        //    }
        //    initButton();//流程按钮


        //}
        ///// <summary>
        ///// 任务指派事件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void taskAssignButtonEvent(object sender, EventArgs e)
        //{

        //    string dlg = "window.open( 'AssignTask.aspx?OperatorInstanceId=" + OperatorInsId + "','newwindow'," +
        //   " 'height=200,width=650,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no')";
        //    if (!this.IsStartupScriptRegistered(UserId))
        //        this.RegisterStartupScript(UserId, "<script>" + dlg + "</script>");


        //}
        ///// <summary>
        ///// 根据任务配置加载流程命令按钮
        ///// </summary>
        //private void initButton()
        //{
        //    DataTable taskCommand = client.GetTaskCommands(WorktaskId);
        //    foreach (DataRow dr in taskCommand.Rows)
        //    {
        //        string cmdName = dr["CommandName"].ToString();
        //        Button btnCommand = new Button();
        //        btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
        //        btnCommand.Text = cmdName;
        //        btnCommand.Click += new EventHandler(runButtonEvent);
        //        cmdBtnPlace.Controls.Add(btnCommand);
        //        Literal lab1 = new Literal();
        //        lab1.Text = "&nbsp;&nbsp;";
        //        cmdBtnPlace.Controls.Add(lab1);
        //    }
        //}
        ///// <summary>
        ///// 提交流程事件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void runButtonEvent(object sender, EventArgs e)
        //{

        //    if (SaveUserControl(false))
        //    {
        //        string command = (sender as Button).Text;
        //        client.Run(UserId, OperatorInsId, command);
        //        Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
        //    }
        //    else
        //    {
        //        throw new Exception("保存业务数据失败，流程无法提交!!");
        //    }
        //}
        //private bool SaveUserControl(bool IsDraft)
        //{
        //    try
        //    {
        //        if (pageState == WorkFlowConst.STATE_VIEW) return true;
        //        foreach (BaseUserControl bc in UserCtrlList)
        //        {
        //            if (bc.CtrlState == WorkFlowConst.STATE_VIEW) continue;
        //            bc.SaveUserControl(IsDraft);
        //        }
        //        return true;
        //    }
        //    catch
        //    {
        //        throw;
        //    }
        //}
        ///// <summary>
        ///// 任务退回事件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void taskBackButtonEvent(object sender, EventArgs e)
        //{
        //    client.TaskBack(UserId, OperatorInsId);
        //    Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
        //}

        /// <summary>
        /// 返回业务表单ID   
        /// </summary>
        /// <param name="cpid"></param>
        /// <returns></returns>
        public string ReturnPayId(string cpid,string entity)
        {
            BCrmPayFlow bCrmPayFlow = new BCrmPayFlow();
            string vcp = bCrmPayFlow.GetTableInfoById(cpid == "" ? Guid.NewGuid() : new Guid(cpid), entity);
            if (vcp != null)
            {
                return vcp.ToString();
            }
            return "";
        }
    }
}